import re

from py_ini_config_modules.system_functions import eprint, read_ini_file


def ini_config_set_nosection(file, var, value, noindent, com_symbol, view_comments, separator=None):
    separator_set = False
    if separator is None:
        separator = '='
    else:
        separator_set = True
    config = read_ini_file(file)
    written = False
    commented_index = -1
    uncommented_index = -1

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if re.fullmatch(f'\s*{com_symbol}*\s*{var}\s*', line[0]):
            if com_symbol not in config[i]:
                uncommented_index = i
            elif len(line) > 1 and line[1] == value:
                commented_index = i
    if commented_index != -1 and view_comments: # 1, 3
        config[commented_index] = config[commented_index].lstrip().lstrip(com_symbol)
        written = True
        if uncommented_index != -1:
            config[uncommented_index] = com_symbol + config[uncommented_index]
    elif uncommented_index != -1: # 2
        if separator.strip() not in config[uncommented_index]:
            # config[i] = var + separator + value
            config[uncommented_index] = config[uncommented_index].rstrip() + separator + value
        elif separator_set:
            indx = config[uncommented_index].index(separator.strip()) - 1
            while config[uncommented_index][indx] == ' ':
                indx -= 1
            config[uncommented_index] = config[uncommented_index][:indx + 1] + separator + value
        else:
            indx = config[uncommented_index].index(separator.strip()) + 1
            while config[uncommented_index][indx] == ' ':
                indx += 1
            config[uncommented_index] = config[uncommented_index][:indx] + value
        written = True
    # if config[i].lstrip().startswith(com_symbol):
    #     config[i] = config[i].lstrip().lstrip(com_symbol).lstrip()
    # written = True
        if noindent:
            config[uncommented_index] = config[uncommented_index].lstrip()
    if not written:
        config.append(var + separator + value)
    return config


def ini_config_comment_nosection(file, var, com_symbol, separator='='):
    config = read_ini_file(file)
    var_commented = False

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if line[0] == var:
            config[i] = com_symbol + config[i]
            var_commented = True
        # Переменные могут встречаться несколько раз
        # elif line[0] == '#' + var:
        #     eprint('Переменная уже была закомментирована')
        #     return False
    if not var_commented:
        eprint('Переменная не найдена')
        return False

    return config


def ini_config_del_nosection(file, var, com_symbol, separator='='):
    config = read_ini_file(file)
    new_config = []
    var_deleted = False
    last_var_index = -1

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            new_config.append(config[i])
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if re.fullmatch(f'\s*{com_symbol}*\s*{var}\s*', line[0]):
            if line[0].lstrip().startswith(com_symbol):
                last_var_index = i
            else:
                var_deleted = True
                continue
        new_config.append(config[i])

    if not var_deleted:
        if last_var_index != -1:
            new_config = new_config[:last_var_index] + new_config[last_var_index + 1:]
        else:
            eprint('Переменная не найдена')
            return False

    while len(new_config) > 0 and new_config[0].strip() == '':
        new_config = new_config[1:]
    while len(new_config) > 0 and new_config[-1].strip() == '':
        new_config = new_config[:-1]
    return new_config


def ini_config_get_nosection(file, var, separator='='):
    config = read_ini_file(file)

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if line[0] == var:
            return line[1] if len(line) > 1 else var
    return False


def ini_config_get_commented_nosection(file, var, com_symbol, separator='='):
    config = read_ini_file(file)

    res = []
    var_without_value_found = False
    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if re.fullmatch(f'\s*{com_symbol}\s*{var}\s*', line[0]):
            # return line[1] if len(line) > 1 else var
            if len(line) > 1:
                res.append(line[1])
            else:
                var_without_value_found = True
    if len(res) > 0:
        # print(res)
        return res
    elif var_without_value_found:
        return [var]
    return False


def ini_config_is_set_nosection(file, var, separator='='):
    config = read_ini_file(file)

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if line[0] == var and len(line) > 1:
            return 0
    return 1


def ini_config_uncomment_nosection(file, var, com_symbol, separator='='):
    config = read_ini_file(file)
    var_uncommented = False
    last_commented_index = -1

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if line[0].startswith(com_symbol) and line[0].lstrip(com_symbol).lstrip() == var:
            last_commented_index = i
        elif line[0] == var:
            eprint('Переменная уже была раскомментирована')
            return False

    if last_commented_index != -1:
        config[last_commented_index] = config[last_commented_index].lstrip().lstrip(com_symbol).lstrip()
        var_uncommented = True

    if not var_uncommented:
        eprint('Переменная не найдена')
        return False
    return config
